package com.fametal.ui.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.fametal.ui.utils.IOUtils;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ThreadReadWriterIOSocket implements Runnable {
	private Socket client;
	private Context mContext;

	public ThreadReadWriterIOSocket(Context context, Socket client) {
		this.client = client;
		mContext = context;
	}

	@Override
	public void run() {
		Log.d(QTService.TAG, Thread.currentThread().getName() + "---->" + "a client has connected to server!");
		BufferedOutputStream out;
		BufferedInputStream in;
		try {
			/* PC端发来的数据msg */
			String currCMD = "";
			out = new BufferedOutputStream(client.getOutputStream());
			in = new BufferedInputStream(client.getInputStream());
			// testSocket();// 测试socket方法
			while (QTService.ioThreadFlag) {
				try {
					if (!client.isConnected()) {
						break;
					}

					/* 接收PC发来的数据 */
					Log.v(QTService.TAG, Thread.currentThread().getName() + "---->" + "will read......");
					/* 读操作命令 */
					currCMD = readCMDFromSocket(in);
					Log.v(QTService.TAG, Thread.currentThread().getName() + "---->" + "**currCMD ==== " + currCMD);

					/* 根据命令分别处理数据 */
					if (currCMD.equalsIgnoreCase("EXIT")) {
						sendBroadcast();
					}
				} catch (Exception e) {
					Log.e(QTService.TAG, Thread.currentThread().getName() + "---->" + "read write error111111");
				}
			}
			out.close();
			in.close();
		} catch (Exception e) {
			Log.e(QTService.TAG, Thread.currentThread().getName() + "---->" + "read write error222222");
			e.printStackTrace();
		} finally {
			try {
				if (client != null) {
					Log.v(QTService.TAG, Thread.currentThread().getName() + "---->" + "client.close()");
					client.close();
				}
			} catch (IOException e) {
				Log.e(QTService.TAG, Thread.currentThread().getName() + "---->" + "read write error333333");
				e.printStackTrace();
			}
		}
	}
	
	private void sendBroadcast() {
		Intent intent=new Intent();  
        intent.setAction("com.fametal.ui.service");  
        intent.putExtra("message","exit");  
        mContext.sendBroadcast(intent); 
	}

	/* 读取命令 */
	public static String readCMDFromSocket(InputStream in) {
		int MAX_BUFFER_BYTES = 2048;
		String msg = "";
		byte[] tempbuffer = new byte[MAX_BUFFER_BYTES];
		try {
			int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);
			msg = new String(tempbuffer, 0, numReadedBytes, "utf-8");
			tempbuffer = null;
		} catch (Exception e) {
			Log.v(QTService.TAG, Thread.currentThread().getName() + "---->" + "readFromSocket error");
			e.printStackTrace();
		}
		// Log.v(Service139.TAG, "msg=" + msg);
		return msg;
	}
}